﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using jQuery.WebControls;

namespace jQuery
{
    internal class Common
    {
        private static Common c;        
        private Common()
        {

        }

        internal static Common Instance
        {
            get 
            {
                if (c == null)
                    c = new Common();
                return c;
            }
        }

        internal void CheckJQueryScriptManager(Page AspPage)
        {
            if (AspPage.Items["jQueryScrMng"] == null)
            {
                jQueryScriptManager jsm = null;
                if (AspPage.Master != null)
                {
                    CheckControls(AspPage.Master.Controls, false, ref jsm);
                }
                if (jsm == null)
                {
                    CheckControls(AspPage.Controls, false, ref jsm);
                }
                if (jsm == null)
                {
                    throw new ArgumentException(jQuery.Messages.CMN_err1);
                }
                AspPage.Items.Add("jQueryScrMng", jsm);                    
            }                      
        }

        internal jQueryScriptManager Get_jQueryScriptManager(Page AspPage)
        {
            CheckJQueryScriptManager(AspPage);
            return AspPage.Items["jQueryScrMng"] as jQueryScriptManager;
        }

        private void CheckControls(ControlCollection cc, bool found, ref jQueryScriptManager jQueryControl)
        {
            for (int i = 0; i < cc.Count; i++)
            {
                if (cc[i].GetType().FullName.Equals("jQuery.WebControls.jQueryScriptManager"))
                {
                    if (!found)
                    {
                        jQueryControl = cc[i] as jQueryScriptManager;
                        found = true;
                    }
                    else
                    {
                        throw new ArgumentException(jQuery.Messages.CMN_err2);
                    }
                    
                }
                if (cc[i].HasControls())
                {
                    CheckControls(cc[i].Controls, found, ref jQueryControl);
                }
            }
        }
    }
}
